// main.js
import {
  createApp
} from 'vue';
import App from './App.vue';
import ElementPlus from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import 'element-plus/dist/index.css';
import router from './router/index';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import axios from 'axios';
import './assets/main.less';
import 'animate.css'; // 引入 animate.css
import {
  cancelAllRequests
} from './services/request'
import {
  createPinia
} from 'pinia';
import piniaPluginPersist from 'pinia-plugin-persist';
import _ from 'lodash';
const app = createApp(App);
app.config.globalProperties.$axios = axios;
app.use(ElementPlus, {
  locale: zhCn,
})
// 引入Element Plus icon 所需
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}

const pinia = createPinia();
pinia.use(piniaPluginPersist);
// pinia.use(({store})=>{
//   const initialState=JSON.parse(JSON.stringify(store.$state))
//   store.$reset=()=>{
//     store.$patch(initialState)
//   }
// })

// 在登录页的路由守卫中
router.beforeEach((to, from, next) => {

  
  // cancelAllRequests();
  const tokenData = JSON.parse(sessionStorage.getItem('token'));
  console.log('323',to.path,tokenData);
  // const hasToken = tokenData && tokenData.token;
  // 如果已经有 token，说明已经登录，则直接进入下一个路由
  if (!tokenData && to.path !== '/login') {
    next('/login');
  } else {
    // 如果没有 token，进入登录页
    next();
  }
});




// 自定义防抖指令
app.directive('debounce', {
  beforeMount(el, binding) {
    const handler = _.debounce(binding.value, 2000);
    if (binding.arg === 'click') {
      el.addEventListener('click', handler);
    } else {
      el.addEventListener('input', handler);
    }
  }
});

// 自定义节流指令
app.directive('throttle', {
  beforeMount(el, binding) {
    const handler = _.throttle(binding.value, 3000);
    if (binding.arg === 'click') {
      el.addEventListener('click', handler);
    } else {
      el.addEventListener('input', handler);
    }
  }
});
app.use(pinia);
app.use(router);


app.mount('#app');